package com.jprocms.module.cms.api;

import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.tenant.core.context.TenantContextHolder;
import com.jpro.framework.tenant.core.service.TenantFrameworkService;
import com.jprocms.module.cms.api.vo.SiteTenantCreateReqVO;
import com.jprocms.module.cms.controller.admin.site.vo.SiteCreateReqVO;
import com.jprocms.module.cms.convert.site.SiteConvert;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.service.site.SiteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;

import static com.jpro.framework.common.pojo.CommonResult.success;
import static com.jprocms.module.cms.constant.CmsSysConstants.CMS_DEFAULT_SITE_ID;

@Slf4j
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class SiteApiImpl implements SiteApi {

    @Resource
    private SiteService siteService;

    @Override
    public CommonResult<Long> createSite(SiteTenantCreateReqVO createReqVO) {
        try {
            TenantContextHolder.setTenantId(TenantContextHolder.DEF_TENANT_ID);
            final SiteDO refSite = siteService.getSite(CMS_DEFAULT_SITE_ID);
            //设置租户数据源切换
            TenantContextHolder.setTenantId(createReqVO.getTenantId());
            final SiteCreateReqVO siteCreateReqVO = SiteConvert.INSTANCE.convert(createReqVO);
            siteCreateReqVO.setTenantId(createReqVO.getTenantId());
            siteCreateReqVO.setParentId(0L);
            final Long siteId = siteService.createTenantSite(siteCreateReqVO, refSite);
            return success(siteId);
        } catch (IOException e) {
            log.error("创建站点失败.{}", e.getMessage());
        }
        return success(0L);
    }

    @Override
    public CommonResult<String> generateSitePath(String sitePath) {
        return success(siteService.generateSitePath(sitePath));
    }
}
